//
//  Date+Extension.swift
//  WeiBoXR
//
//  Created by acer on 16/9/29.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit


extension Date {
    static func sinaDate(creatAt: String) -> Date {
    
        let dt = DateFormatter()
        //  指定格式化方式
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dt.locale = Locale(identifier: "en_US")
        let creatAtDate = dt.date(from: creatAt)!
        
        return creatAtDate
    }
    
//    get 方法
    var sinaDateString: String {
        let dt = DateFormatter()
        dt.locale = Locale(identifier: "en_US")
        
        if isThisYear(creatAtDate: self) {
            
            let currentCalendar = Calendar.current
            if currentCalendar.isDateInToday(self) {
                
                let timeinterVal: TimeInterval = abs(self.timeIntervalSinceNow)
                if timeinterVal < 60 {
                    return "刚刚"
                } else if timeinterVal < 3600 {
                    let result = timeinterVal / 60
                    return "\(Int(result))分钟前"
                } else {
                    let result = timeinterVal / 3600
                    return "\(Int(result))小时前"
                }
            } else if currentCalendar.isDateInYesterday(self) {
                
                dt.dateFormat = "昨天 HH:mm"
            } else {
                dt.dateFormat = "MM-dd HH:mm"
                
            }
            
        } else {
            print("不是今年")
            dt.dateFormat = "yyyy-MM-dd HH:mm"
            
        }
        
        return dt.string(from: self)
}
    
    private func isThisYear(creatAtDate: Date) -> Bool {
        let dt = DateFormatter()
        dt.dateFormat = "yyyy"
        dt.locale = Locale(identifier: "en_US")
        let creatAtYear = dt.string(from: creatAtDate)
        let currentYear = dt.string(from: Date())
        
        return creatAtYear == currentYear
    }

}
